<template>
  <el-dialog
      v-model="dialogVisible"
      title="批量导出表格"
      width="80%"
      :before-close="handleClose"
  >
    <div class="export-content">
      <!-- 字段选择区域 -->
      <div class="field-selection">
        <p class="section-label">字段选择区域 <el-icon><QuestionFilled /></el-icon></p>
        <div class="field-tags">
          <el-tag
              v-for="field in fields"
              :key="field.key"
              class="field-tag"
              :effect="field.selected ? 'light' : 'plain'"
              @click="toggleField(field)"
          >
            {{ field.label }}
          </el-tag>
        </div>
      </div>

      <!-- 表格预览区域 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          :border="true"
          class="export-table"
      >
        <el-table-column
            v-for="field in selectedFields"
            :key="field.key"
            :prop="field.key"
            :label="field.label"
            :min-width="field.width || 120"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleExport">下载Excel</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {exportPaper} from "@/api/Manage/paper.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  papers: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const fields = ref([
  { key: 'title', label: '标题', selected: true, width: 200 },
  { key: 'paperType', label: '论文类型', selected: true },
  { key: 'journalName', label: '期刊名', selected: true, width: 180 },
  { key: 'indexing', label: '期刊收录', selected: true },
  { key: 'impactFactor', label: '影响因子', selected: true },
  { key: 'issn', label: '期刊ISSN', selected: true },
  { key: 'volumeNumber', label: '卷', selected: true },
  { key: 'issueNumber', label: '期', selected: true },
  { key: 'pageRange', label: '页码', selected: true },
  { key: 'publishDate', label: '发表年份', selected: true },
  { key: 'authorRank', label: '我的排名', selected: true },
  { key: 'doi', label: 'DOI', selected: true },
  { key: 'authorInfo', label: '作者列表', selected: true, width: 200 }
])

const selectedFields = computed(() => fields.value.filter(f => f.selected))

const tableData = ref([])

watch(() => props.papers, (newPapers) => {
  tableData.value = newPapers.map(paper => ({
    ...paper,
    indexing: paper.indexing ? paper.indexing.join(', ') : '',
    publishDate: new Date(paper.publishDate).getFullYear(),
    authorInfo: paper.authorInfo ? paper.authorInfo.map(author => author.name).join(', ') : ''
  }))
}, { immediate: true })

const toggleField = (field) => {
  field.selected = !field.selected
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleCancel = () => {
  dialogVisible.value = false
  ElMessage.info('已取消导出')
}

const handleExport = async () => {
  const selectedFields = fields.value.filter(f => f.selected);
  if (selectedFields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段');
    return;
  }

  // 提取选中的字段键名
  const selectedFieldKeys = selectedFields.map(field => field.key);

  // 提取表格数据中选中的字段
  const exportData = tableData.value.map(paper => {
    const filteredPaper = {};
    selectedFieldKeys.forEach(key => {
      filteredPaper[key] = paper[key];
    });
    return filteredPaper;
  });

  // 发送数据到后端
  try {
    const response = await exportPaper({
      fields: selectedFields,
      data: exportData
    });


    if (response.status === 200) {
      const blob = response.data; // 直接使用 response.data，因为 responseType 是 'blob'
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'exported_papers.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      ElMessage.success('导出成功');
    } else {
      const errorText = response.data; // 使用 response.data 获取错误信息
      console.error('导出失败:', errorText);
      ElMessage.error('导出失败');
    }
  } catch (error) {
    if (error.response) {
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      console.error('导出失败:', error.response.data);
      ElMessage.error('导出失败: ' + error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('导出失败: 请求未收到响应');
      ElMessage.error('导出失败: 请求未收到响应');
    } else {
      // 在设置请求时发生了一些事情，触发了错误
      console.error('导出失败:', error.message);
      ElMessage.error('导出失败: ' + error.message);
    }
  }

  dialogVisible.value = false;
};


</script>

<style scoped>
.export-content {
  padding: 20px 0;
}

.field-selection {
  margin-bottom: 24px;
}

.section-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.field-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.field-tag {
  cursor: pointer;
  user-select: none;
}

.field-tag:hover {
  border-color: #409eff;
}

.export-table {
  margin-top: 20px;
  border-radius: 4px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

